package com.example.server.transport;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.channel.socket.nio.NioSelector;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: yuanjianpeng
 * @Date: 2019/5/18 12:00
 * @Description: Netty客户端，用于与TX交互数据
 */
@Component
public class NettyClient implements InitializingBean { //实现InitializingBean意味着在一开始就启动netty连接TX

    public NettyClientHandler clientHandler;

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    @Override
    public void afterPropertiesSet() throws Exception {
        start("localhost", 8080);
    }

    public void start(String hostName, Integer port) {
        clientHandler = new NettyClientHandler();

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline channelPipeline = socketChannel.pipeline();
                        channelPipeline.addLast("decoder", new StringDecoder());
                        channelPipeline.addLast("encoder", new StringEncoder());
                        channelPipeline.addLast("handler",clientHandler);
                    }
                });

        try {
            bootstrap.connect(hostName, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        (ChannelInitializer)(socketChannel) -> {
//            ChannelPipeline channelPipeline = socketChannel.;
//            channelPipeline.addLast("decoder", new StringDecoder());
//            channelPipeline.addLast("encoder", new StringEncoder());
//            channelPipeline.addLast("handler",clientHandler);
//        }
    }

    public void send(JSONObject jsonObject) {
        clientHandler.call(jsonObject);
    }
}
